package com.example.contentclient;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.contentclient.Util.PermissionUtil;

public class PermissionLazyActvity extends AppCompatActivity implements View.OnClickListener {
    private  static final String[] PERMISSIONS_CONTACTS=new String[]{
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS
    };
    private  static final String[] PERMISSIONS_SMS=new String[]{
            Manifest.permission.READ_SMS,
            Manifest.permission.SEND_SMS
    };
    private static final int REQUEST_CODE_CONTACTS=1;
    private static final int REQUEST_CODE_SMS=2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission_lazy);
        findViewById(R.id.btn_contact).setOnClickListener(this);
        findViewById(R.id.btn_sms).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_contact:
                PermissionUtil.checkPermission(this,PERMISSIONS_CONTACTS,REQUEST_CODE_CONTACTS);

                break;
            case R.id.btn_sms:
                PermissionUtil.checkPermission(this,PERMISSIONS_SMS,REQUEST_CODE_SMS);

                break;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode)
        {
            case REQUEST_CODE_CONTACTS:
                if(PermissionUtil.checkGrant(grantResults))
                {
                    Log.d("tang","获取通讯录权限成功");
                }
                else
                {
                    Log.d("tang","获取通讯录权限失败!");
                    //如果权限获取失败，我们让它自动跳转到权限设置界面
                    jumpToSetting();
                }
                break;
            case REQUEST_CODE_SMS:
                PermissionUtil.checkGrant(grantResults);
                if(PermissionUtil.checkGrant(grantResults))
                {
                    Log.d("tang","获取短信收发权限成功");
                }
                else
                {
                    Log.d("tang","获取短信收发权限失败!");

                }
                break;
        }
    }

    private void jumpToSetting() {
        Intent intent=new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package",getPackageName(),null));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
